package com.huiminpay.merchant.service.impl;

import com.aliyun.oss.OSS;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.merchant.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 有点儿意思
 * @Description:
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    OSS oss;
    
    @Value("${oss.aliyun.bucket}")
    String bucket;
    @Value("${oss.aliyun.domain}")
    String domain;

    /**
     * 上传文件功能
     *
     * @param file 文件
     * @return 文件地址
     */
    @Override
    public String upload(MultipartFile file) {
        //1.获取原始文件名
        String filename = file.getOriginalFilename();
        if (!StringUtils.isEmpty(filename)){
            //2.获取文件扩展名
            String ext = filename.substring(filename.lastIndexOf("."));
            filename = System.currentTimeMillis()+ext;
            try {
                oss.putObject(bucket, filename, file.getInputStream());
                //生成网络路径
                return domain+filename;
            } catch (IOException e) {
                throw new BusinessException(CommonErrorCode.E_100106);
            }
        }
        return null;
    }
}
